#!usr/bin/env python
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tap_connector11_redis.py
@version:
@time: 2022/01/13 
"""
import json

import redis
from TapClientConnector.connector.tap_connector00_base import *


class TAPRedisConnector(TAPConnectorBase):
    data_struct = 'list'

    def __init__(self, kwargs):
        super().__init__(kwargs)
        host = self.FORMAT_DB_INFO.get('host')
        port = self.FORMAT_DB_INFO.get('port')
        db = self.FORMAT_DB_INFO.get('database')
        password = self.FORMAT_DB_INFO.get('password')
        if self.FORMAT_DB_INFO.get('data_struct'):
            self.data_struct = self.FORMAT_DB_INFO.get('data_struct')
        self.connector = redis.Redis(
            host=host,
            port=port,
            db=db,
            password=password,
            decode_responses=True
        )

    @connector_exec_logger
    def _exec(self, data):
        operate = data.get('operate')
        name = data.get('table')
        if operate == 'drop':
            exist = self.connector.exists(name)
            if exist:
                self.connector.delete(name)
            else:
                logger.warning(f'redis {name} not exist')
        else:
            raise NotSupport

    def _query(self, query_data):
        table = query_data.get('table')
        data = []
        if self.data_struct == 'list':
            self.TABLE_DESCRIPTION = self.connector.lrange(table, 0, 0)[0].split(',')
            # column = self.connector.lindex(table, 0).split(',')
            # column_len = len(column)
            raw_data = self.connector.lrange(table, 1, -1)
            for one in raw_data:
                _raw = one.split(',')
                # redis 查询出来的全是string，需要自己转换成int
                row_data = []
                for raw_one in _raw:
                    try:
                        raw_one = float(raw_one)
                        raw_one = int(raw_one)
                    except ValueError:
                        pass
                    row_data.append(raw_one)
                data.append(tuple(row_data))
                data.sort()
        elif self.data_struct == 'json':
            all_tables = self.show_tables()
            for one in all_tables:
                if f'{table}_' in one:
                    data.append(json.loads(self.connector.get(one)))
        return data

    @connector_query_logger
    def show_tables(self):
        result = self.connector.execute_command('keys', '*')
        return result

    @generate_logger
    def generate_drop(self, table):
        if table:
            self.CURRENT_TABLE = table
        return {
            'operate': 'drop',
            'table': table
        }

    # ** DML **
    @generate_logger
    def generate_select(self, column='*', where=None, table=None, order=''):
        if table:
            self.CURRENT_TABLE = table
        return {
            'column': column,
            'where': where,
            'table': table,
            'order': order
        }


if __name__ == '__main__':
    from TapDataSourceInfo.db_info_pdk import Redis

    config = Redis.AUTO_REDIS_TARGET01
    T = TAPRedisConnector(config)
    print(T._query({'table': 'b_ora1661743538566606182'}))
    print(T.TABLE_DESCRIPTION)
    # print(T.connector.lrange('dummy_list', 1, -1))
    # print(T.show_tables())
    # print(type(T.connector.lindex('robot', 1)))
    # T.connector.delete('robot')
    # print(T.connector.get('dummy_json_35c8a7b3-08ef-4daa-8d37-f7e466b4b1d0_mgn0ih0d'))
    # print(type(T.connector.get('dummy_json_35c8a7b3-08ef-4daa-8d37-f7e466b4b1d0_mgn0ih0d')))

    # drop
    # print(drop := T.generate_drop('list'))
    # T.exec(drop)

    # query list
    # print(query := T.generate_select(table='B_MARIADB1660651019453393178'))
    # T.data_struct = 'list'
    # print(T.query(query))
    #
    # # query json
    # print(query := T.generate_select(table='one_1'))
    # T.data_struct = 'json'
    # print(T._query(query))
